package pt.fct.mpc.lastfm.artist;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import pt.fct.mpc.lastfm.R;
import pt.fct.mpc.lastfm.connectivity.LastfmBluetoothUnavailableException;
import pt.fct.mpc.lastfm.connectivity.LastfmURL;
import pt.fct.mpc.lastfm.generic.ImageActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class ArtistImagesActivity extends Activity {

	private static final String TAG = "Last.fm Artist Activity";
	private boolean gotImages = false;
	ArtistData artistDataSet = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.artist_images);

		// Reads the info sent by the intent
		Intent the_intent_that_gave_life_to_everything = getIntent();
		Bundle intent_data = the_intent_that_gave_life_to_everything
				.getExtras();

		if (intent_data == null) {
			Log.e(TAG, "No extra data");
			finish();
		}

		artistDataSet = (ArtistData) intent_data
				.getSerializable("artistserial");

		if (artistDataSet == null) {
			Log.e(TAG, "Null values from bundle: albumDataSet = "
					+ artistDataSet);
			finish();
		}

		if (!gotImages)
			getImages();
		createImagesTab();
	}

	private void createImagesTab() {
		GridView g = (GridView) findViewById(R.id.artist_images);
		g.setAdapter(new ImageAdapter(this));

		g.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ImageData imgData = artistDataSet.getImages().get(position);
				String imgUrl = imgData.getImage_original();

				if (imgUrl == "") {
					imgUrl = imgData.getImage_extralarge();
					if (imgUrl == "") {
						imgUrl = imgData.getImage_large();
						if (imgUrl == "") {
							imgUrl = imgData.getImage_medium();
							if (imgUrl == "") {
								imgUrl = imgData.getImage_small();
								if (imgUrl == "")
									return;
							}
						}
					}
				}

				Bundle intent_data = new Bundle();
				intent_data.putString("url", imgUrl);

				Intent intent = new Intent(getApplicationContext(),
						ImageActivity.class);
				intent.putExtras(intent_data);
				startActivity(intent);
			}
		});
	}

	public class ImageAdapter extends BaseAdapter {
		private Context mContext;
		List<ImageData> imgList = artistDataSet.getImages();

		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return imgList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(126, 126));
				imageView.setAdjustViewBounds(false);
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imageView.setPadding(8, 8, 8, 8);
			} else {
				imageView = (ImageView) convertView;
			}

			String url = imgList.get(position).getImage_largesquare();
			Bitmap img = urlToImage(url);
			imageView.setImageBitmap(img);
			return imageView;
		}

	}

	private void getImages() {
		String artist_name = artistDataSet.getName();
		try {
			artist_name = URLEncoder.encode(artistDataSet.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException("encoding problems");
		}

		String request_params = "?method=artist.getimages" + "&artist="
				+ artist_name + "&limit=10" + "&api_key="
				+ getString(R.string.lastfm_api_key);

		String request_str = getString(R.string.lastfm_api_url)
				+ request_params;

		LastfmURL request_url = null;
		try {
			request_url = new LastfmURL(request_str);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = null;
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		XMLReader xr = null;
		try {
			xr = sp.getXMLReader();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		ImagesXmlHandler myImagesXmlHandler = new ImagesXmlHandler();
		xr.setContentHandler(myImagesXmlHandler);

		try {
			xr.parse(new InputSource(request_url.openStream()));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		request_url.finished();

		artistDataSet.setImages(myImagesXmlHandler.getParsedData());

		this.gotImages = true;
	}

	private Bitmap urlToImage(String imageUrl) {

		LastfmURL myFileUrl = null;
		try {
			myFileUrl = new LastfmURL(imageUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		InputStream is = null;
		try {
			is = myFileUrl.openStream();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LastfmBluetoothUnavailableException e) {
			e.printStackTrace();
		}

		myFileUrl.finished();

		return BitmapFactory.decodeStream(is);
	}
}